package com.lizongbo.seotijian.web.servlets.cgi;

import java.io.File;
import java.io.IOException;
import java.net.URL;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public abstract class AbstractCgi implements Cgi {

	@Override
	public void doCgi(String cgiName, String param, HttpServletRequest req,
			HttpServletResponse resp) throws ServletException, IOException {
		String format = ".html";
		for (int i = 0; i < FORMATS.length; i++) {
			String paramL = param.toLowerCase();
			if (paramL.endsWith(FORMATS[i])) {
				format = FORMATS[i];
			}
		}
		doCgiInternal(cgiName, param, req, resp);
		String viewUrl = "/WEB-INF/cgi-bin/" + this.getCgiName() + "/result_"
				+ format.substring(1) + ".jsp";
		System.out.println("render by " + viewUrl);
		String fileurl = req.getSession().getServletContext().getRealPath(
				viewUrl);
		try {
			System.out.println("fileurl ==" + fileurl);
			if (!new File(fileurl).exists()) {
				System.err.println(fileurl + " is not exists");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		req.getRequestDispatcher(viewUrl).forward(req, resp);
	}

	abstract protected void doCgiInternal(String cgiName, String param,
			HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException;
}
